﻿using System;
using System.Collections;
using System.Web;
using System.Web.Caching;

namespace Core.Library
{
    public class DataCaching
    {
        public static object GetCache(string key)
        {
            return HttpContext.Current.Cache.Get(key);
        }

        public static void InsertCache(string key, object data, double expireTime)
        {
            if (expireTime == 0) InsertCacheNoExpireTime(key, data);
            else HttpContext.Current.Cache.Insert(key, data, null, DateTime.Now.AddMinutes(expireTime), Cache.NoSlidingExpiration);
        }

        public static void InsertCacheNoExpireTime(string key, object data)
        {
            if (data != null) HttpContext.Current.Cache.Insert(key, data);
        }

        public static bool RemoveCache(string key)
        {
            if (HttpContext.Current.Cache[key] == null)
                return false;
            HttpContext.Current.Cache.Remove(key);
            return true;
        }

        public static object GetHashCache(string hashKey, object param)
        {
            var retVal = (Hashtable)GetCache(hashKey);
            if (retVal == null) return null;
            if (retVal[param] == null) return null;
            return retVal[param];
        }

        public static void SetHashCache(string hashKey, object param, double expireTime, object data)
        {
            var retVal = (Hashtable)GetCache(hashKey);
            if (retVal == null)
            {
                retVal = new Hashtable();
                retVal[param] = data;
                InsertCache(hashKey, retVal, expireTime);
            }
            else if (retVal.ContainsKey(param))
            {
                retVal[param] = data;
            }
            else
            {
                retVal.Add(param, data);
            }
        }
        public static void RemoveAll()
        {
            Cache cache = HttpContext.Current.Cache;
            IEnumerator ienum = cache.GetEnumerator();
            while (ienum.MoveNext())
            {
                var dic = (DictionaryEntry)ienum.Current;
                RemoveCache(dic.Key.ToString());
            }
        }
        public static ArrayList GetKeys()
        {
            IEnumerator dcEnum = HttpContext.Current.Cache.GetEnumerator();
            var cacheArray = new ArrayList();
            while (dcEnum.MoveNext())
                if (((DictionaryEntry)dcEnum.Current).Value != null)
                    cacheArray.Add(((DictionaryEntry)dcEnum.Current).Key.ToString());
            cacheArray.Sort();
            return cacheArray;
        }
    }
}